package com.lingshi.shopping_pay_service.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.lingshi.shopping.entity.CartGoods;
import com.lingshi.shopping.entity.Orders;
import com.lingshi.shopping.entity.Payment;
import com.lingshi.shopping.enums.ErrorEnums;
import com.lingshi.shopping.enums.OrderStatusEnums;
import com.lingshi.shopping.exception.BusException;
import com.lingshi.shopping.service.OrdersService;
import com.lingshi.shopping.service.ZfbPayService;
import com.lingshi.shopping_pay_service.config.ZfbPayConfig;
import com.lingshi.shopping_pay_service.mapper.PaymentMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@DubboService
public class ZfbPayServiceImpl implements ZfbPayService {

    @Autowired
    private AlipayClient alipayClient;

    @DubboReference
    private OrdersService ordersService;

    @Autowired
    private ZfbPayConfig zfbPayConfig;

    @Autowired
    private PaymentMapper paymentMapper;



    @Override
    public String pcPay(Orders orders) {

        if (!OrderStatusEnums.UNPAID.getCode().equals(orders.getStatus())) {
            throw new BusException(ErrorEnums.ORDER_PAID_ERROR);
        }


        // 构造请求参数以调用接口
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        //设置回调地址
        request.setNotifyUrl(zfbPayConfig.getNotifyUrl().concat(zfbPayConfig.getPcNotify()));


        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();

        // 设置商户订单号
        model.setOutTradeNo(orders.getId());

        // 设置订单总金额
        model.setTotalAmount(orders.getPayment().toString());


        List<CartGoods> cartGoods = orders.getCartGoods();

        // 设置订单标题
        model.setSubject(cartGoods.get(0).getGoodsName());


        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                //返回二维码
                return response.getQrCode();
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    @Override
    public boolean checkSign(Map<String, String> params) {

        try {
            return AlipaySignature.rsaCheckV1(params, zfbPayConfig.getPublicKey(), "utf-8", "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public void updateOrderStatus(Map<String, String> params) {

        //获取订单号
        String orderId = params.get("out_trade_no");
        //获取支付状态
        String tradeStatus = params.get("trade_status");

        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            Orders orders = ordersService.findById(orderId);
            orders.setStatus(OrderStatusEnums.PAID.getCode());
            orders.setPaymentTime(new Date());
            //修改订单
            ordersService.update(orders);
        }
        //创建支付记录
        Payment payment = new Payment();
        payment.setOrderId(orderId);
        payment.setTransactionId(params.get("trade_no"));
        payment.setTradeType("支付宝");
        payment.setPayerTotal(NumberUtil.toBigDecimal(params.get("total_amount")));
        payment.setTradeState(tradeStatus);

        //获取参数，转换成Map——>JSON 存储到数据库
        payment.setContent(JSONUtil.toJsonStr(params));
        payment.setCreateTime(new Date());
        //保存支付记录
        paymentMapper.insert(payment);

    }

}
